package com.wyd.flowable;

import lombok.extern.slf4j.Slf4j;
import org.flowable.common.engine.api.delegate.event.AbstractFlowableEventListener;
import org.flowable.common.engine.api.delegate.event.FlowableEngineEventType;
import org.flowable.common.engine.api.delegate.event.FlowableEvent;
import org.flowable.engine.TaskService;
import org.flowable.identitylink.service.impl.persistence.entity.IdentityLinkEntity;
import org.flowable.task.service.impl.persistence.entity.TaskEntityImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class FlowableEventListener2 extends AbstractFlowableEventListener {
    @Autowired
    private TaskService taskService;

    @Override
    public void onEvent(FlowableEvent event) {
        log.info("进入全局监听 event={} class={} type={}", event, event.getClass(), event.getType().getClass());

        if (event.getType() == FlowableEngineEventType.TASK_CREATED) {
            // 用户任务创建完成
            if (event instanceof org.flowable.common.engine.impl.event.FlowableEntityEventImpl) {
                org.flowable.common.engine.impl.event.FlowableEntityEventImpl eventImpl = (org.flowable.common.engine.impl.event.FlowableEntityEventImpl) event;
                TaskEntityImpl taskEntity = (TaskEntityImpl) eventImpl.getEntity();

                log.info("taskEntity={}", taskEntity);

                // 可以设置成功 但是只能进入一次
                String tr = tr(taskEntity.getAssignee());
                if (tr != null) {
//                    taskEntity.setAssignee(tr); // 这种方式 历史任务中的执行人未修改
//                    taskEntity.setCategory("");
                    taskService.setAssignee(taskEntity.getId(), tr);
                }

                for (IdentityLinkEntity identityLink : taskEntity.getIdentityLinks()) {
                    tr = tr(identityLink.getUserId());
                    if (tr != null) {
//                        identityLink.setUserId(tr);
                        taskService.deleteCandidateUser(taskEntity.getId(), identityLink.getUserId());
                        taskService.addCandidateUser(taskEntity.getId(), tr);
                    }
                }
            }

            // 测试修改任务执行人看行不
            // 如果多次移交？

        }


    }

    private String tr(String userId) {
        if (userId == null) {
            return null;
        }

        switch (userId) {
            case "1":
                return "11";
            case "2":
                return "22";
            case "3":
                return "33";
        }

        return null;
    }

    @Override
    public boolean isFailOnException() {
        return true;
    }
}
